package br.com.pucrs.tcc.login;

import java.io.IOException;

import javax.faces.context.FacesContext;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class SessionFilter implements Filter {
	public void init(FilterConfig config) {
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;

		try {
			if (httpRequest.isRequestedSessionIdValid()) {
				FacesContext context = FacesContext.getCurrentInstance();
				HttpSession httpSession = ((HttpServletRequest) request)
						.getSession(false);
				SessionType session = null;
				if (httpSession.getAttribute("user-session") != null) {
					session = (SessionType) httpSession.getAttribute("user-session");
				}

				if (session == null) {
					HttpServletResponse httpResponse = (HttpServletResponse) response;
					httpResponse.sendRedirect(httpRequest.getContextPath()
							+ "/index.xhtml");
				} else {
					chain.doFilter(request, response);
				}
			} else {
				HttpServletResponse httpResponse = (HttpServletResponse) response;
				httpResponse.sendRedirect(httpRequest.getContextPath()
						+ "/index.xhtml");

			}
		} catch (Exception e) {
			HttpServletResponse httpResponse = (HttpServletResponse) response;
			httpResponse.sendRedirect(httpRequest.getContextPath()
					+ "/erro.xhtml");
		}
	}

	public void destroy() {
	}
}
